/*
 * Copyright (C) 2023 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"

#define BUFFER_SIZE 5U
static int product_number = 0;
osSemaphoreId_t empty_id;

void producer_thread(void *arg) {
    (void)arg;
    while(1) {
        osSemaphoreAcquire(empty_id, osWaitForever);
        product_number++;
        printf("[producer_thread]%s produces a product, now product number: %d.\r\n", osThreadGetName(osThreadGetId()), product_number);

        osDelay(100);
    }
}

void consumer_thread(void *arg) {
    (void)arg;
    while(1){
        if(osSemaphoreGetCount(empty_id) < BUFFER_SIZE){
        osSemaphoreRelease(empty_id);
        product_number--;
        printf("[consumer_thread]%s consumes a product, now product number: %d.\r\n", osThreadGetName(osThreadGetId()), product_number);
        }
        osDelay(100);
    }
}

static void TestTask(void)
{
    empty_id = osSemaphoreNew(BUFFER_SIZE, BUFFER_SIZE, NULL);  
    osThreadAttr_t attr;
    attr.name = "producer";
    attr.stack_size = 1024*4;
    attr.priority = osPriorityNormal;

    if(osThreadNew((osThreadFunc_t)producer_thread, NULL, &attr) == NULL){
        printf("Failed to create producer_thread!\n");
    };
    attr.name = "consumer";
    if(osThreadNew((osThreadFunc_t)consumer_thread, NULL, &attr) == NULL){
        printf("Failed to create consumer_thread!\n");
    };
}

APP_FEATURE_INIT(TestTask);
